#include "tcp.hpp"
#include "Protocol.hpp"
using namespace MY_TCP;
#include <stdio.h>
#include <stdlib.h>

void Usage(std::string command)
{
  std::cout << command << " ip port" << std::endl;
}

void ShortLink(int sock)
{
  std::string OpAll = "+-*/";
  int x = rand() % 1000;
  int y = rand() % 1000;
  char op = OpAll[rand() % 4];
  request_t req(x, y, op);
  // 序列化
  std::string req_str = SerializeRequest(req);
  send(sock, req_str.c_str(), req_str.size(), 0);
  char res_str[1024];
  recv(sock, res_str, sizeof(res_str), 0);
  // 反序列化
  response_t res;
  DeSerializeResponse(res_str, res);
  if (res.code != 0)
  {
    std::cerr << "错误计算，错误码:" << res.code << std::endl;
    exit(2);
  }
  else
  {
    std::cout << x << op << y << " = " << res.result << std::endl;
  }
}
void LongLink(int sock)
{
  while (true)
  {
    sleep(3);
    std::string OpAll = "+-*/";
    int x = rand() % 1000;
    int y = rand() % 1000;
    char op = OpAll[rand() % 4];
    request_t req(x, y, op);
    // 序列化
    std::string req_str = SerializeRequest(req);
    send(sock, req_str.c_str(), req_str.size(), 0);
    char res_str[1024];
    recv(sock, res_str, sizeof(res_str), 0);
    // 反序列化
    response_t res;
    DeSerializeResponse(res_str, res);
    if (res.code != 0)
    {
      std::cerr << "错误计算，错误码:" << res.code << std::endl;
      //exit(2);
    }
    else
    {
      std::cout << x << op << y << " = " << res.result << std::endl;
    }
  }
}
struct ip_port
{
  std::string _ip;
  int _port;
  ip_port(std::string ip, int port) : _ip(ip), _port(port) {}
};
void *run(void *argv)
{
  // pthread_detach(pthread_self());
  ip_port s = *(ip_port *)argv;
  int sock = TCP_SOCK::Sock();
  TCP_SOCK::Connect(sock, s._ip, s._port);
  // 使用服务
  // 1.短链接
   ShortLink(sock);
  // 2.长链接
 // LongLink(sock);

  close(sock);
}

int main(int args, char *argv[])
{
  if (args != 3)
  {
    std::cerr << "use error" << std::endl;
    Usage(argv[0]);
    exit(1);
  }
  srand((unsigned int)time(nullptr));
  pthread_t client[5];
  ip_port *s = new ip_port(argv[1], atoi(argv[2]));

  for (int i = 0; i < 5; i++)
  {
    pthread_create(client + i, nullptr, run, (void *)s);
  }
  for (int i = 0; i < 5; i++)
  {
    pthread_join(*(client + i), nullptr);
  }
  return 0;
}
